﻿namespace Luka;

/// <summary>
/// 数字类型扩展
/// </summary>
public static class NumberExtensions
{
    /// <summary>
    /// double转decimal
    /// </summary>
    /// <returns></returns>
    public static decimal ToDecimal(this double num) => (decimal)num;

    /// <summary>
    /// double转decimal
    /// </summary>
    /// <param name="precision">小数位数</param>
    /// <param name="mode">四舍五入策略</param>
    /// <returns></returns>
    public static decimal ToDecimal(this double num, int precision, MidpointRounding mode = MidpointRounding.AwayFromZero) => Math.Round((decimal)num, precision, mode);

    /// <summary>
    /// float转decimal
    /// </summary>
    /// <returns></returns>
    public static decimal ToDecimal(this float num) => (decimal)num;

    /// <summary>
    /// float转decimal
    /// </summary>
    /// <param name="precision">小数位数</param>
    /// <param name="mode">四舍五入策略</param>
    /// <returns></returns>
    public static decimal ToDecimal(this float num, int precision, MidpointRounding mode = MidpointRounding.AwayFromZero) => Math.Round((decimal)num, precision, mode);

    /// <summary>
    /// 四舍五入
    /// </summary>
    public static double ToRound(this double num, int digit) => Math.Round(num, digit, MidpointRounding.AwayFromZero);

    /// <summary>
    /// 四舍五入
    /// </summary>
    public static decimal ToRound(this decimal num, int digit) => Math.Round(num, digit, MidpointRounding.AwayFromZero);

    /// <summary>
    /// 四舍五入
    /// </summary>
    public static decimal? ToRound(this decimal? num, int digit) => Math.Round(num.GetValueOrDefault(), digit, MidpointRounding.AwayFromZero);

    /// <summary>
    /// 取正数
    /// </summary>
    public static int ToPositiveNumber(this int str) => str < 0 ? 0 : str;
}